package com.cddeskywebsite.servlet;

import com.cddeskywebsite.bean.NewsBean;
import com.cddeskywebsite.dao.NewsDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 1.接受post网址 /newsAdd。jsp
 * 2.接收到传递过来的新闻参数 新闻标题 新闻内容
 * 3.完成新闻的添加
 * 4.使当前网页刷新(或者跳转到其他页面)
 */
@WebServlet("/newsEdit.jsp")
public class NewsUpdateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        // 获取请求参数
        String newsTitle = req.getParameter("upd_NewsTitle");
        String newsContent = req.getParameter("upd_NewsContent");

        // 获取并验证新闻ID
        String newsIdParam = req.getParameter("newsId");
        if (newsIdParam == null || newsTitle == null || newsContent == null) {
            req.setAttribute("msg", "参数缺失");
            req.setAttribute("url", "news.jsp");
            req.getRequestDispatcher("WEB-INF/pages/error.jsp").forward(req, resp);
            return;
        }

        int newsId;
        try {
            newsId = Integer.parseInt(newsIdParam);
        } catch (NumberFormatException e) {
            req.setAttribute("msg", "无效的新闻ID");
            req.setAttribute("url", "news.jsp");
            req.getRequestDispatcher("WEB-INF/pages/error.jsp").forward(req, resp);
            return;
        }

        // 实例化新闻对象并设置属性
        NewsBean newsBean = new NewsBean();
        newsBean.setNewsID(newsId);
        newsBean.setNewsTitle(newsTitle);
        newsBean.setNewsContent(newsContent);

        // 实例化新闻DAO对象
        NewsDao newsDao = new NewsDao();

        // 更新新闻记录
        int result = newsDao.update(newsBean);

        // 检查更新结果
        if (result > 0) {
            resp.sendRedirect("news.jsp");
        } else {
            req.setAttribute("msg", "更新失败");
            req.setAttribute("url", "news.jsp");
            req.getRequestDispatcher("WEB-INF/pages/error.jsp").forward(req, resp);
        }
    }

}
